#!/usr/bin/python

import os, sys, socket
import pygame
from pygame.locals import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled'

def load_image(name, colorkey=None):
    fullname = os.path.join('monkeyPorn', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
	return image, image.get_rect()

class FluffyBunny:	
	def __init__(self, name, id, image):
		self.bunny_id = id
		self.frame = 0
		self.position = (0,0)
		self.velocity = (0,0)
		self.oldPosition = None
		self.image = image
		self.back = pygame.Surface((34, 34))
		self.name = name
		self.timer = None
		self.flag = 1
	
	def set(self, x, y, frame):
		self.position = (x, y)
		self.frame = frame

	def update(self):
		self.position = (self.position[0] + self.velocity[0], self.position[1] - self.velocity[1])
		vely = self.velocity[1] - 4
		velx = 0
		if vely < -4:
			vely = -4
		if self.velocity[0] != 0:
			if self.velocity[0] > 0:
				velx = -1
			else:
				velx = 1
		self.velocity = (self.velocity[0]+velx, vely)

	def draw(self, screen):
		if self.oldPosition != None:
			# Replace background.
			screen.blit(self.back, self.oldPosition)
		# Get background.
		self.back.blit(screen, (0,0), (self.position[0], self.position[1], 34, 34))
		self.oldPosition = self.position
		# Draw foreground.
		screen.blit(self.image, self.position, ((34*self.frame)+(4*self.frame),  (34*self.bunny_id)+(2*self.bunny_id), 32, 32))


class SpriteManager:
	def __init__(self, screen):
		self.spriteList = []
		self.screen = screen

	def add(self, sprite):
		self.spriteList.append(sprite)

	def update (self):
		for i in self.spriteList:
			i.update()

	def draw(self):
		for i in self.spriteList:
			i.draw(self.screen)

pygame.init()
screen = pygame.display.set_mode((800, 600))

rabbitList = SpriteManager(screen)


# gameStates
menu = 1
playing = 2
scoreBoard = 3

gameState = menu

background, backsize = load_image('menu.png',-1)
rabbitImage, rabbitSize = load_image('rabbit.png', (0,0,0))

screen.blit(background, (0, 300-(backsize[3]/2)))

players = 1

player1 = FluffyBunny(sys.argv[0], 0, rabbitImage)
rabbitList.add(player1)

player1.set(100,300,0)

if players == 2:
	# change this to be the second player
	player2 = FluffyBunny(sys.argv[0])


HOST = 'localhost'    # The remote host
PORT = 1337              # The same port as used by the server
sock = None
# We don't know what this does, so if someone reads this PLEASE TELL US! PS: Server seems to require it... ;-)
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
		sock = socket.socket(af, socktype, proto)
    except socket.error, msg:
		sock = None
		continue
    try:
		sock.connect(sa)
    except socket.error, msg:
		sock.close()
		sock = None
		continue
    break
if sock is None:
    print 'could not open socket'
    sys.exit(1)

#sock.send('Hello, world')
#i = 0
#while i < 10:
#	i += 1
#	data = sock.recv(1024)
#	print 'Received', repr(data)

def playerUp(rabbit):
	if rabbit.flag == 1:
		rabbit.flag = 0
		rabbit.limit = 0
	else:
		rabbit.limit += 1
		rabbit.velocity = (rabbit.velocity[0], 8)
	if rabbit.limit > 10:
		rabbit.flag = 1

def playerLeft(rabbit):
	velx = rabbit.velocity[0]
	velx -= 10
	if velx < -10:
		velx = -10
	rabbit.velocity = (velx, rabbit.velocity[1])

def playerRight(rabbit):
	velx = rabbit.velocity[0]
	velx += 10
	if velx > 10:
		velx = 10
	rabbit.velocity = (velx, rabbit.velocity[1])


keylist = []
keylist.append((K_UP, playerUp, player1))
keylist.append((K_LEFT, playerLeft, player1))
keylist.append((K_RIGHT, playerRight, player1))
if players == 2:
	keylist.append((K_w, playerUp, player2))
	keylist.append((K_a, playerLeft, player2))
	keylist.append((K_d, playerRight, player2))


running = 1
while running:
	for event in pygame.event.get():
		if event.type == pygame.QUIT: 
			running = 0
	
	if pygame.key.get_pressed()[pygame.K_ESCAPE]:
		if gameState == menu:
			running = 0
		elif gameState == scoreBoard:
			gameState = menu
		elif gameState == playing:
			gameState = scoreBoard
	
	for key in keylist:
		if pygame.key.get_pressed()[key[0]]:
			key[1](key[2])
	# Update and draw all rabbits.
	rabbitList.update()
	rabbitList.draw()
	# Refresh screen.
	pygame.display.flip()


socket.close()





